<?php
/**
 * Created by PhpStorm.
 * User: hedx
 * Date: 2016/3/30
 * Time: 17:11
 */

namespace common\mq;


use business\base\services\IdGenerationService;
use business\base\services\MessageTemplateService;
use common\mq\models\MessageAttributes;
use common\mq\models\MessageServiceLogModel;
use common\mq\models\MessageServiceModel;
use common\mq\utils\MessageUtils;
use common\utils\DateTimeUtil;
use common\utils\DateTimeUtils;
use common\utils\GUIDUtil;
use Exception;

class MessageServiceHelper
{
    //消息批次生成时的key
    const MESSAGE_BATCH_ID_GENERATION = "message_service_batch_generation";
    //消息批次的最短长度
    const MESSAGE_BATCH_MIN_LENGTH = 8;

    /**
     * 直接发送给阿里云消息服务并保存消息到消息主表
     *
     * @param $queueName
     * @param MessageAttributes $messageAttributes
     * @param array $params
     */
    public static function sendFastSimpleMessage($queueName, $messageAttributes, $params = [])
    {
        //消息属性处理
        $messageAttributes = self::handleMessageAttributes($queueName, $messageAttributes, $params);

        //如果队列名和内容不为空，则解析消息并发给阿里云消息服务
        if (!empty($queueName) && !empty($messageAttributes->getContent())) {
            $mqService = MessageServiceFactory::getMessageService();
            $messageBody = MessageUtils::getMessageBodyByAttributes($messageAttributes, $queueName);
            //message_type: 1 => 队列模型, 2 => 订阅发布模型
            if ($messageAttributes->getType() == MessageServiceModel::MESSAGE_TYPE_TOPIC) {
                //发布/订阅模型
                $sendResult = $mqService->publishMessage($queueName, $messageBody);
            } else {
                $priority = $messageAttributes->getPriority();
                $delay = $messageAttributes->getDelaySeconds();
                $sendResult = $mqService->sendMessage($queueName, $messageBody, $priority, $delay);
            }
            //保存发送日志
            self::saveSendLog($queueName, $messageAttributes, $sendResult);
        }
    }

    /**
     * 处理消息属性的默认值设置等工作
     * @param string $queueName
     * @param MessageAttributes $messageAttributes
     * @param array $params
     * @return MessageAttributes
     */
    private static function handleMessageAttributes($queueName, $messageAttributes, $params)
    {
        //去掉默认的批次
        /*if (empty($messageAttributes->getBatch())) {
            $messageAttributes->setBatch(self::getNextMessageBatch());
        }*/
        //默认优先级在MessageUtils里面设定(无默认设定则为8)
        if (empty($messageAttributes->getPriority())) {
            $messageAttributes->setPriority(MessageUtils::getPriority($queueName));
        }
        //默认无延时时间
        if (empty($messageAttributes->getDelaySeconds())) {
            $messageAttributes->setDelaySeconds(0);
        }
        //默认采用队列模型
        if (empty($messageAttributes->getType())) {
            $messageAttributes->setType(MessageServiceModel::MESSAGE_TYPE_QUEUE);
        }
        //默认参数替换
        if (!empty($params)) {
            $content = MessageUtils::replaceVariable($messageAttributes->getContent(), $params);
            $messageAttributes->setContent($content);
            $title = MessageUtils::replaceVariable($messageAttributes->getTitle(), $params);
            $messageAttributes->setTitle($title);
        }
        return $messageAttributes;
    }

    /**
     * 保存消息发送日志
     * @param $queueName
     * @param MessageAttributes $message
     * @param array $sendResult
     */
    private static function saveSendLog($queueName, MessageAttributes $message, array $sendResult)
    {
        $status = $sendResult['isSuccess'] ? MessageServiceLogModel::SEND_SUCCESS : MessageServiceLogModel::SEND_FAILED;
        $remark = $sendResult['isSuccess'] ? '发送成功' : $sendResult['errMsg'];
        $logModel = new MessageServiceLogModel();
        $logModel->queue_name = $queueName;
        $logModel->message_id = $sendResult['messageId'];
        $logModel->message_content = $message->getContent();
        $logModel->status = $status;
        $logModel->remark = $remark;
        $logModel->created_time = DateTimeUtils::now();
        $logModel->save();
    }

}